import { login, logout, getInfo, getRouters, getRoleRouters } from "@/api/erp_api/login";
import { imgUrl, getKpiPostNotice } from "@/utils/ty.js"
import { getUserProfile } from "@/api/system/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import defAva from "@/static/images/profile.jpg";
import { defineStore } from "pinia";
import useSetStore from '@/store/modules/set.js'
export interface LoginForm {
  username: string;
  password: string;
  code: string;
  uuid: string;
}
const useUserStore = defineStore("user", {
  state: () => ({
    token: getToken(),
    name: "",
    avatar: "",
    roles: Array(),
    permissions: [],
		user: {},
		userParent: null,
		userPost: null,
		userSalesman: null,
		isSalesman: false,
		userWarehouse: null,
		userKpiPosts: null,
		regionCode: '',
		navigation: [],
    menu: [],
		pages: [],
		profile: null,
		postGroup: '',
		roleGroup: '',
    rolesList: [],
		roleName: '',
		roleId: '',
		roleKey: '',
		watermark: '',
		warehouseId: '',
		warehouseName: '',
		kpiPostsId: '',
		kpiPostsName: '',
		permissionsOther: {
			isKpiPost: false,
			isKpiPostNotice: false,
			isKpiPostTarget: false
		}
  }),
  actions: {
    // 登录
    login(userInfo: LoginForm) {
      const username = userInfo.username.trim();
      const password = userInfo.password;
      const code = userInfo.code;
      const uuid = userInfo.uuid;
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid)
          .then((res: any) => {
            setToken(res.token);
            this.token = res.token;
            resolve(null);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 获取用户信息
    getInfo() {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res: any) => {
						this.navigation = res.navigation
            const user = res.user;
            const avatar =
              user.avatar == "" || user.avatar == null
                ? defAva
                : imgUrl(user.avatar);
            if (res.roles && res.roles.length > 0) {
              // 验证返回的roles是否是一个非空数组
              this.roles = res.roles;
              this.permissions = res.permissions;
            } else {
              this.roles = ["ROLE_DEFAULT"];
            }
						if (user.roles && user.roles.length > 0) {
						  // 验证返回的roles是否是一个非空数组
						  this.rolesList = user.roles || []
							const roleData = uni.getStorageSync('tyRole')
							const isRoleData = this.rolesList.filter((item: any) => item.roleId === roleData.roleId)
							if (roleData && isRoleData.length > 0) {
								this.roleName = isRoleData[0].roleName
								this.roleId = isRoleData[0].roleId
								this.roleKey = isRoleData[0].roleKey
							} else {
								this.roleName = user.roles[0].roleName
								this.roleId = user.roles[0].roleId
								this.roleKey = user.roles[0].roleKey
							}
						}
						this.setRole({
							roleName: this.roleName,
							roleId: this.roleId
						})
						this.watermark = `<p>${user.userName}</p><p>${user.nickName}</p><p>${user.phonenumber}</p>`
            this.name = user.userName;
            this.avatar = avatar;
            this.user = user;
						useSetStore().getMenuClicks(user.userId, this.roleId)
						if ((this.permissions as string[]).includes('zhouyz:kpiPostNotice:list')) {
							getKpiPostNotice(user.userId)
						}
						// const filter = res.permissions.filter((item: any) => item.indexOf('salesman') > -1)
						// console.log(filter)
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
		// 切换角色
		setRole(data: any) {
			this.roleName = data.roleName
			this.roleId = data.roleId
			uni.setStorageSync('tyRole', {
				roleName: data.roleName,
				roleId: data.roleId
			})
			this.getRoleRouters(this.roleId)
		},
		// 获取用户信息2
		getUserProfile() {
		  return new Promise((resolve, reject) => {
		    getUserProfile()
		      .then((res: any) => {
		        this.profile = res.data;
		        this.regionCode = res?.regionCode || ''
		        this.roleGroup = res.roleGroup;
		        this.userParent = res.parent ? res.parent : null
						this.userPost = res.defaultPost ? res.defaultPost : null
						this.userSalesman = res.salesman ? res.salesman : null
						this.isSalesman = res.salesman ? true : false
						this.userWarehouse = res.warehouse ? res.warehouse : null
						this.userKpiPosts = res.kpiPosts ? res.kpiPosts : null
						if (res.warehouse) {
							this.warehouseId = res.warehouse.id
							this.warehouseName = res.warehouse.name
						} else {
							this.warehouseId = ''
							this.warehouseName = ''
						}
						let kpiPostsNameAll = ''
						if (res.kpiPosts) {
							this.kpiPostsId = res.kpiPosts[0]?.id
							this.kpiPostsName = `${res.kpiPosts[0]?.userPostName}【${res.kpiPosts[0]?.level}】`
							kpiPostsNameAll = res.kpiPosts.map((item: any) => `${item.userPostName}【${item.level}】`).join(',')
						} else {
							this.kpiPostsId = ''
							this.kpiPostsName = ''
						}
						this.postGroup = kpiPostsNameAll ? `${kpiPostsNameAll}/ ${res.postGroup}` : res.postGroup;
						resolve(res);
		      })
		      .catch((error) => {
		        reject(error);
		      });
		  });
		},
		// 获取用户菜单
		getRouters() {
		  return new Promise((resolve, reject) => {
		    getRouters().then((res: any) => {
		        this.menu = res.data;
		        resolve(res);
		      })
		      .catch((error) => {
		        reject(error);
		      });
		  });
		},
		// 获取用户角色菜单
		getRoleRouters(roleId: any) {
		  return new Promise((resolve, reject) => {
		    getRoleRouters(roleId).then((res: any) => {
		        this.menu = res.data;
						this.pages = menuArr(res.data) as []
		        resolve(res);
		      })
		      .catch((error) => {
		        reject(error);
		      });
		  });
		},
    // 退出系统
    logOut() {
      return new Promise<null>((resolve, reject) => {
        logout()
          .then(() => {
            this.token = "";
            this.roles = [];
            this.permissions = [];
            this.name = "";
            this.avatar = "";
            removeToken();
            resolve(null);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
  },
});

// 处理菜单
function menuArr (menu: any) {
	const newMenu = []
	for(let i = 0 ; i < menu.length; i++) {
		if (menu[i].children) {
			const children = menu[i].children.map(item => {
				return {
					...item,
					page: `pages/${menu[i].path.replace(/^\//, '')}/${item.path.replace(/^\//, '')}`
				}
			})
			newMenu.push(...children)
		}
	}
	return newMenu
}

export default useUserStore;
